# -*-coding: utf-8 -*-
# by zw on 2017/12/20
import logging
from utils.util import get_valid_yaml, merge_dicts
from sanic import response
from utils.mongo import get_env_config_collection, get_app_config_collection, get_global_template_collection
from sanic import Blueprint

bp = Blueprint('env', url_prefix='')
_logger = logging.getLogger(__name__)


@bp.get("env_config")
async def get_env_config(request):
    try:
        env = request.raw_args['env']
        type = request.raw_args['type']
        _logger.info(" env %s host %s", env, request.host)
        env_config = get_env_config_collection().find_one({"env": env, "type": type}, {"_id": 0})
        return response.json({"code": 0, "message": "", "data": env_config, })
    except Exception as e:
        _logger.exception("url %s exception %s" % (request.url, e))
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})


@bp.post("env_config")
async def add_env_config(request):
    try:
        _json = request.json
        env = _json["env"]
        type = _json["type"]
        yaml_str = _json["yaml_str"]
        _logger.info(" env %s config %s host %s", env, yaml_str, request.host)
        get_env_config_collection().find_one_and_update({"env": env, "type": type},
                                                              {"$set": {"yaml_str": yaml_str}},
                                                              upsert=True)

    except Exception as e:
        _logger.exception("url %s" % request.url)
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})
    else:
        return response.json({"code": 0, "message": "", "data": {}})
